package FlexTrade.Auctions;

//import Customer;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

import FlexTrade.AbstractAuction;

import common_classes.AuctionPrimitiveData;
import common_classes.AuctionStates;
import common_classes.BidPriceData;
import common_classes.IAuction;
import common_classes.WSEvent;


public final class DutchAuctionImpl extends AbstractAuction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 327427899130056608L;

	AdjustDutchPrice adjust;
	Thread runThread;
	
	public DutchAuctionImpl(String _uniqueAuctionID) {
		this.uniqueAuctionID = _uniqueAuctionID;
		auctionStates = new AuctionStates();
		eventPool = new Hashtable<String, ArrayList<WSEvent>>();
	}
	
	public DutchAuctionImpl(){
		auctionStates = new AuctionStates();
		eventPool = new Hashtable<String, ArrayList<WSEvent>>();
	}
		
	public DutchAuctionImpl(AuctionPrimitiveData _auctionPrimitiveData) {
		// TODO Auto-generated constructor stub
		auctionStates = new AuctionStates();
		auctionStates.acceptableBidPrice = _auctionPrimitiveData.acceptablePrice;
		this.auctionPrimitiveData = _auctionPrimitiveData;
		this.uniqueAuctionID = _auctionPrimitiveData.uniqueAuctionID;
		eventPool = new Hashtable<String, ArrayList<WSEvent>>();
		adjust = new AdjustDutchPrice(_auctionPrimitiveData.askingPrice,
										_auctionPrimitiveData.reservcePrice,
										_auctionPrimitiveData.timeDuration);
		adjust.setDutchAuction(this);
		runThread = new Thread(adjust, "RunThread");
		runThread.start();
	}

	@Override
	public boolean receiveNewAcceptablePriceFromProvider(float newAcceptablePrice)
																throws RemoteException {
		// TODO Auto-generated method stub
		this.auctionStates.acceptableBidPrice = newAcceptablePrice;
		//fireNotify(IAuction.D_ACCEPTABLE_PRICE_RECEIVED);
		putEventToPool(IAuction.D_ACCEPTABLE_PRICE_RECEIVED);
		return true;
	}

	@Override
	public boolean receivePriceAcceptanceFromCustomer(BidPriceData _bidPriceData)
			throws RemoteException {
		// TODO Auto-generated method stub
		this.auctionStates.acceptableBidPrice = _bidPriceData.bidPrice;
		this.auctionStates.highestBidCustomer = _bidPriceData.customer;
		this.lastBidPriceData = _bidPriceData;
		//fireNotify(IAuction.D_CUSTOMER_ACCEPT);
		adjust.stopDutchAuction();
		putEventToPool(IAuction.D_CUSTOMER_ACCEPT);
		putEventToPool(IAuction.D_AUCTION_FINISH);
		return true;
	}

	
	public void setAuctionTimeDuration(long timeInMicroSecond) {
	    Date timeToRun = new Date(System.currentTimeMillis() + timeInMicroSecond);
	    Timer timer = new Timer();
	    timer.schedule(new TimerTask() {
	            public void run() {
	                // Task here ...
	            	//fireNotify(IAuction.D_AUCTION_TIMEOUT);
	            	putEventToPool(IAuction.D_AUCTION_TIMEOUT);
	            }
	        }, timeToRun);
	}
}
